import React from 'react';
import UserModel from "../../../model/user";
import {
    Button,
    Input,
    PageHeader,
    Popconfirm,
    Select,
    Table,
    Radio,
} from "antd";
import Admin from "../../../layout/Admin";
import Tags from "./tags";
import Info from "../../../service/info";
import log from "../../../service/log"
import {defaultAvatarSrc} from "../../../component/CusomHeader/CusomHeader";
import {dayDiff, defaultEnd, defaultStart,} from "../user-total/user-total";
import UserDetailModal from "../components/user-detail-modal";
import UserTagModal from "../components/user-tag-modal";
import AddVipModal from "../components/add-vip-modal";
import AddCouponModal from "../components/add-coupon-modal";
import UserActivityModal from "../components/user-activity-modal";
import UserBehaviorModal from "../components/user-behavior-modal";
import PaginationFooter from "../../../component/PaginationFooter/PaginationFooter";
import SendUserMsgModal from "../components/send-user-msg-modal";
import AddSuperVipModal from "../components/add-super-vip-modal";

const { Option } = Select

const levelArr = [-1,]

for (let i = 0; i < 50; i++) {
    let lv = i + 1
    levelArr.push(lv)
}

const tags = Tags.map((tag, i) => ({title: tag, index: i,}))

class UserList extends React.Component {

    constructor(props) {
        super(props)
        this.model = new UserModel()
        this.tags = tags
        this.state = {
            account: '',
            addVipInt: 0,
            mark: this.markToTags(0),
            lv: -1,
            status: -1,
            vip: -1,
            p: 0,
            list: [],
            user: {},
            deposit: [],
            fuwu: [],
            jinbi: [],
            daoju: [],
            jubao: [],
            userTags: [],
            newUserTags: [],
            coupon: null,
            couponCount: 0,
            searchType: 0,
            black: false,
            offset: 0,
            limit: 10,
            dayDiff: dayDiff,
            start: defaultStart,
            end: defaultEnd,
            zhuanfa: 0,
            xinwen: 0,
            shiping: 0,
            liaotian: [],
            shichang: 0,
            behavior: [],
            modal: {
                user: false,
                tag: false,
                addVip: false,
                addSuperVip: false,
                addCoupon: false,
                activity: false,
                behavior: false,
                sendMsg: false,
            },
        }
    }

    componentDidMount() {
        this.all()
    }

    submit = () => {

        const account = this.state.account
        const mark = this.markToTags(0)
        const lv = -1
        const status = -1
        const vip = -1
        const searchType = this.state.searchType
        if (searchType === 'nickname') {
            const nick = this.state.account
            this.getByName({nick})
        } else {
            this.setState({
                account,
                mark,
                lv,
                status,
                vip,
            }, () => {
                this.fetchPage(0)
            })
        }


    }

    all = () => {

        let p = this.state.p
        let mark = this.tagsToMark(this.state.mark)
        let lv = this.state.lv
        let status = this.state.status
        let vip = this.state.vip
        let account = this.state.account

        this.model
            .all({p, mark, lv, status, vip, account,})
            .then((resp) => {
                const list = resp.data.ok || []
                list.forEach((p, i) => p.key = (i + 1).toString())
                this.setState({
                    list,
                })
            })

    }

    black = () => {
        let offset = this.state.offset
        let limit = this.state.limit
        this.model
            .black({offset, limit,})
            .then(resp => {
                const list = resp.data.ok
                list.forEach((p, i) => p.key = (i + 1).toString())
                this.setState({
                    list,
                })
            })

    }

    delete = () => {
        return this.model
            .delete({
                act: this.state.user.U.Username,
            })
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('删除成功')
                }
            })
    }

    getByName = (params) => {
        this.model
            .getByName(params)
            .then(resp => {

                const list = resp.data.ok
                list.forEach((p, i) => p.key = (i + 1).toString())
                this.setState({list,})
            })
    }

    addVip = () => {

        const user = this.state.user
        const month = this.state.addVipInt
        const act = user.U.Username
        this.model
            .addVip({act, month,})
            .then((resp) => {
                const ok = resp.data.ok
                if (ok === 1) {
                    Info.success('修改成功')
                    this.modalCancel('addVip')
                }
            })

    }

    behavior = () => {
        const id = this.state.user.U.Id
        return this.model.behavior({
                uid: id,
                start: this.formatTime(this.state.start),
                end: this.formatTime(this.state.end),
            })
            .then(resp => {
                console.log(resp)
                if (resp.data.ok) {
                    this.setState({
                        behavior: resp.data.ok,
                    })
                }
            })
    }

    deleteUser = (user) => {

        this.setState({
            user: user,
        }, () => {
            this.delete()
                .then(() => {
                    this.all()
                })
        })

    }

    addCoupon = () => {
        const uid = this.state.user.U.Id
        const propid = this.state.coupon.value
        const propnum = this.state.couponCount
        this.model
            .addCoupon({uid, propid, propnum,})
            .then(resp => {
                const r = resp.data.ok
                if (r === 1) {
                    Info.success('添加成功')
                } else {
                    Info.error('添加失败')
                }
            })
            .then(() => {
                this.setState({
                    couponCount: 0,
                    modal: {
                        addCoupon: false,
                    }
                })
            })
            .then(() => this.all())
    }

    fetchPage = (p) => {

        const black = this.state.black

        if (black) {
            const offset = this.state.offset
            this.setState({
                p,
                offset: 10 * p,
            }, () => {
                this.black()
            })
        } else {
            this.setState({
                p,
            }, () => {
                this.all()
            })
        }

    }

    prevPage = () => {

        const p = this.state.p - 1
        this.fetchPage(p)

    }

    nextPage = () => {

        const p = this.state.p + 1
        this.fetchPage(p)

    }

    modalShow = (key) => {

        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true
            },
        })

    }

    modalCancel = (key) => {

        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false
            },
        })
        if (key === 'tag') {
            this.setState({
                newUserTags: [],
            })
        }

    }

    markToTags = (mark) => {

        const m = mark
        const b = m.toString(2)
        const l = Tags.length
        let markString = ''
        if (l > b.length) {
            markString += '0'.repeat(l - b.length)
            markString += b
        } else {
            markString = b
        }

        // const mark = user.U.Mark.toString(2).split().reverse().join()
        const arr = []
        markString = markString.split('').reverse().join('')
        for (let i = 0; i < markString.length; i++) {
            let char = markString[i]
            if (Number(char) === 1) {
                let key = i
                let value = i
                let label = Tags[i]
                arr.push({key, value, label,})
            }
        }
        return arr

    }

    tagsToMark = (tags) => {


        let mark = 0
        for (let i = 0; i < tags.length; i++) {
            let value = tags[i].value
            mark += 1 << value
        }
        return mark

    }

    callUserModal = user => {
        const m = user.U.Mark
        this.setState({
            user,
            newUserTags: this.markToTags(m),
            // newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('user')
        })
    }

    callAddTagModal = user => {

        const m = user.U.Mark
        this.setState({
            user,
            newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('tag')
        })

    }

    callAddVipModal = user => {

        this.setState({
            user,
            // newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('addVip')
        })

    }

    callAddSuperVipModal = user => {

        this.setState({
            user,
            // newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('addSuperVip')
        })

    }

    callSendMsgModal = (user) => {
        this.setState({
            user,
            // newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('sendMsg')
        })
    }

    callAddCouponModal = user => {
        this.setState({
            user,
            // newUserTags: this.markToTags(m),
        }, () => {
            this.modalShow('addCoupon')
        })
    }

    callActivityModal = user => {
        this.setState({
            user,
        }, () => {
            this.modalShow('activity')
        })
    }

    callBehaviorModal = user => {
        this.setState({
            user,
        }, () => {
            this.behavior()
                .then(() => {
                    this.modalShow('behavior')
                })
        })
    }

    onSelectChange = (value, option, type) => {

        this.setState({
            [type]: value
        })
        this.fetchPage(0)

    }

    onTagSelectChange = (value) => {
        this.setState({newUserTags: value,})
    }

    onCouponSelectChange = value => {
        this.setState({coupon: value,})
    }

    onAddVipInputChange = (value) => {
        this.setState({
            addVipInt: value,
        })
    }

    setTags = () => {
        const tags = this.state.newUserTags
        let uid = this.state.user.U.Id
        let mark = this.tagsToMark(tags)
        this.model
            .setTag({mark, uid,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('修改标签成功')
                }
            })
            .then(this.all())
    }

    formatTime = (moment) => {
        return parseInt(moment.format('X'))
    }

    defaultColRender = (text) => text

    render() {

        const black = this.state.black
        const byNickname = this.state.searchType === 'nickname'

        const header = <div style={{background: '#fff'}}>
            <PageHeader title='用户列表'/>
        </div>

        const accountRender = (text, record) => {
            const detail = record.U
            const {
                Nickname,
                Iconurl,
                Username,
            } = detail
            return <div style={{display: 'flex',}}>
                <img alt='' src={Iconurl ? Iconurl : defaultAvatarSrc} style={{height: 40, width: 40, marginRight: '8px',}}/>
                <div>
                    <span style={{display: 'block'}}>昵称: {Nickname}</span>
                    <span style={{display: 'block'}}>账号: {Username}</span>
                </div>
            </div>
        }

        const vipRender = (text, record) => {
            return <div>
                {record.U.Vip}天
            </div>
        }

        const superVipRender = (text, record) => {
            return <div>
                {record.U.Supervip}天
            </div>
        }

        const lvRender = (text, record) => {
            const detail = record.U
            const {
                Viplevel,
            } = detail
            return <div>
                {Viplevel}
            </div>
        }

        const coinRender = (text, record) => {
            const detail = record.U
            const {
                Gold,
            } = detail
            return <div>
                {Gold}
            </div>
        }

        const depositRender = (text, record) => {
            const {Num, Total,} = record
            return <div>
                {/*{Gold}*/}
                <span style={{display: 'block',}}>金额: {Total}</span>
                <span>笔数: {Num}</span>
            </div>
        }

        const IPRender = (text, record) => {
            const detail = record.U
            const {
                Ip,
            } = detail
            return <div>
                {/*{Gold}*/}
                <span style={{display: 'block',}}>{Ip}</span>
            </div>
        }

        const createAt = (text, record) => {
            const {Createt,} = record.U
            return <div>
                <span>{Createt}</span>
            </div>
        }

        const actionRender = (text, record) => {

            return <div>
                <div>
                    <a
                        style={{marginRight: 8,}}
                        onClick={() => this.callUserModal(record)}
                    >
                        <span>查看</span>
                    </a>

                    <a
                        style={{marginRight: 8,}}
                        onClick={() => this.callAddTagModal(record)}
                    >
                        <span>加标签</span>
                    </a>

                    <a
                        onClick={() => this.callAddVipModal(record)}
                        style={{marginRight: 8,}}
                    >
                        <span>加VIP</span>
                    </a>

                    <a
                        onClick={() => this.callAddSuperVipModal(record)}
                        style={{marginRight: 8,}}
                    >
                        <span>加高级VIP</span>
                    </a>

                    <a
                        onClick={() => this.callSendMsgModal(record)}
                    >
                        <span>私信</span>
                    </a>
                </div>

                <div>
                    <Popconfirm
                        title='确定删除用户?'
                        onConfirm={() => this.deleteUser(record)}
                    >
                        <a
                            style={{marginRight: 8,}}
                        >
                            <span>删除用户</span>
                        </a>
                    </Popconfirm>


                    <a
                        onClick={() => this.callAddCouponModal(record)}
                        style={{marginRight: 8,}}
                    >
                        <span>加道具</span>
                    </a>

                    <a
                        onClick={() => this.callActivityModal(record)}
                        style={{marginRight: 8,}}
                    >
                        <span>活跃度</span>
                    </a>

                    <a
                        onClick={() => this.callBehaviorModal(record)}
                    >
                        <span>用户行为</span>
                    </a>
                </div>

            </div>
        }

        const columns = [
            {
                title: '纳米ID',
                render: accountRender,
            },
            {
                title: '会员',
                render: vipRender,
            },
            {
                title: '高级会员',
                render: superVipRender,
            },
            {
                title: '用户等级',
                render: lvRender,
            },
            {
                title: '金币',
                render: coinRender,
            },
            {
                title: '充值金额',
                render: depositRender,
            },
            {
                title: '注册时间',
                render: createAt,
            },
            {
                title: 'IP地址',
                render: IPRender,
            },

            {
                title: '操作',
                dataIndex: '操作',
                render: actionRender,
            },
        ]

        const footer = <PaginationFooter
            pageIndex={this.state.p}
            prevPage={this.prevPage}
            nextPage={this.nextPage}
        />

        const selectStyle = {
            width: 120,
            marginRight: '8px',
        }

        const tagsOptions = this.tags.map(tag => {
            return <Option value={tag.index} key={tag.index}>{tag.title}</Option>
        })

        const table = <div className='list-container'>

            <div
                style={{
                    marginBottom: '16px',
                    // display: 'flex',
                }}
            >

                <div
                    style={{
                        marginBottom: '16px',
                        // display: 'flex',
                    }}
                >
                    <Radio.Group
                        disabled={byNickname}
                        value={this.state.black}
                        defaultChecked={false}
                        onChange={(e => {
                            this.setState({
                                black: e.target.value,
                            }, () => {
                                const black = this.state.black
                                if (black) {
                                    this.black()
                                } else {
                                    this.all()
                                }
                            })
                        })}
                    >
                        <Radio value={false}>正常</Radio>
                        <Radio value={true}>黑名单</Radio>
                    </Radio.Group>

                    <Select
                        disabled={black || byNickname}
                        defaultValue={this.state.vip}
                        value={this.state.vip}
                        placeholder="用户属性"
                        style={selectStyle}
                        onChange={(value, option) => this.onSelectChange(value, option, 'vip')}
                    >
                        <Option value={-1}>会员+非会员</Option>
                        <Option value={0}>非会员</Option>
                        <Option value={1}>会员</Option>
                    </Select>

                    <Select
                        disabled={black || byNickname}

                        // defaultValue="lucy"
                        labelInValue
                        placeholder="用户标签"
                        mode="multiple"
                        value={this.state.mark}
                        style={selectStyle}
                        onChange={(value, option) => this.onSelectChange(value, option, 'mark')}
                    >
                        {tagsOptions}
                    </Select>

                    <Select
                        disabled={black || byNickname}
                        defaultValue={this.state.lv}
                        value={this.state.lv}
                        placeholder="用户等级"
                        style={selectStyle}
                        onChange={(value, option) => this.onSelectChange(value, option, 'lv')}
                    >
                        {levelArr.map(lv => {
                            if (lv === -1) return <Option value={lv} key={lv}>所有等级</Option>
                            return <Option value={lv} key={lv}>lv {lv}</Option>
                        })}
                    </Select>
                </div>

                <Input.Group compact>
                    <Select
                        disabled={black}
                        defaultValue='0'
                        placeholder="搜索条目"
                        style={selectStyle}
                        onChange={(option) => {
                            if (option === 'nickname') {
                                Info.warning('昵称只支持精准搜索')
                            }
                            this.setState({
                                searchType: option,
                            })
                        }}
                    >
                        <Option value="0">账号</Option>
                        <Option value="nickname">昵称</Option>
                        {/*<Option value="uid">UID</Option>*/}
                    </Select>
                    <Input
                        disabled={black}
                        style={{ width: '30%', marginRight: '8px', }}
                        defaultValue="" placeholder="关键字"
                        value={this.state.account}
                        onChange={e => this.setState({account: e.target.value,})}
                    />
                    <Button
                        onClick={this.submit}
                        disabled={black}
                    >提交</Button>
                </Input.Group>

            </div>

            <Table
                dataSource={this.state.list}
                columns={columns}
                // rowKey={(record, index) => index}
                pagination={false}
            />

            {footer}

        </div>

        return <>
            <UserDetailModal
                user={this.state.user.U}
                visible={this.state.modal.user}
                onCancel={() => {
                    this.modalCancel('user')
                    this.setState({
                        user: {},
                    })
                }}
                setUserDetail={(user) => {
                    this.setState({
                        user: {
                            ...this.state.user,
                            U: {
                                ...user,
                            }
                        },
                    })
                }}
                fetchAll={() => this.all()}
            />
            <UserTagModal
                user={this.state.user.U}
                visible={this.state.modal.tag}
                onCancel={() => this.modalCancel('tag')}
                fetchAll={() => this.all()}
            />
            <AddVipModal
                user={this.state.user.U}
                visible={this.state.modal.addVip}
                onCancel={() => this.modalCancel('addVip')}
                fetchAll={() => this.all()}
            />
            <AddSuperVipModal
                user={this.state.user.U}
                visible={this.state.modal.addSuperVip}
                onCancel={() => this.modalCancel('addSuperVip')}
                fetchAll={() => this.all()}
            />
            <AddCouponModal
                user={this.state.user.U}
                visible={this.state.modal.addCoupon}
                onCancel={() => this.modalCancel('addCoupon')}
                fetchAll={() => this.all()}
            />
            <UserActivityModal
                user={this.state.user.U}
                visible={this.state.modal.activity}
                onCancel={() => this.modalCancel('activity')}
                // activity={this.state.modal.activity}
            />
            <UserBehaviorModal
                user={this.state.user.U}
                visible={this.state.modal.behavior}
                onCancel={() => this.modalCancel('behavior')}
            />
            <SendUserMsgModal
                user={this.state.user.U}
                visible={this.state.modal.sendMsg}
                onCancel={() => this.modalCancel('sendMsg')}
            />
            <Admin>
                {header}
                {table}
            </Admin>
        </>
    }
}

export default UserList
